package com.wei.lawyer.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.wei.lawyer.R;
import com.wei.lawyer.model.EditorDataBean;
import com.wei.lawyer.model.ProvinceBean;
import com.wei.lawyer.model.UserBean;
import com.wei.lawyer.net.presenter.UserPresenter;
import com.wei.lawyer.utils.ImageUtils;
import com.wei.lawyer.utils.LogUtils;
import com.wei.lawyer.utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：赵若位
 * 时间：2018/11/1 12:53
 * 邮箱：1070138445@qq.com
 * 功能：编辑个人资料
 */
public class ModifyUserActivity extends BaseActivity<UserPresenter>
{
    @Bind(R.id.img_heade)
    ImageView mImgHeade;
    @Bind(R.id.tv_nick_text)
    TextView mTvNickText;
    @Bind(R.id.tv_descript_text)
    TextView mTvDescriptText;
    @Bind(R.id.tv_sex_text)
    TextView mTvSexText;
    @Bind(R.id.tv_city_text)
    TextView mTvCityText;

    private ImageUtils mUtils = new ImageUtils(this);
    private UserBean mUser = null;

    private List<ProvinceBean> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();
    private OptionsPickerView mLocationPickView, mSexPickView;


    @Override
    protected int getLayoutResource()
    {
        return R.layout.activity_modify;
    }

    @Override
    protected void setStatusBarColor()
    {

    }


    @Override
    protected UserPresenter createPresenter()
    {
        return new UserPresenter(this, this);
    }

    @Override
    protected void initView(Bundle savedInstanceState)
    {
        super.initView(savedInstanceState);
        setLeftBack();
        setTitle(getString(R.string.tv_setting_modify));
        setLocationPickData();
        setSexPickData();
    }

    @Override
    protected void initData()
    {
        super.initData();
        mPresenter.getUserInfo();
    }


    /*获取省市区三级联动数据源*/
    private void setLocationPickData()
    {
        Flowable.create(new FlowableOnSubscribe<List<ProvinceBean>>()
        {
            @Override
            public void subscribe(FlowableEmitter<List<ProvinceBean>> e) throws Exception
            {
                Gson gson = new Gson();
                String json = StringUtils.getJson(mActivity, "City.json");
                options1Items = gson.fromJson(json, new TypeToken<List<ProvinceBean>>()
                {
                }.getType());
                e.onNext(options1Items);
                e.onComplete();
            }
        }, BackpressureStrategy.BUFFER)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(new Function<List<ProvinceBean>, List<List<String>>>()
                {
                    @Override
                    public List<List<String>> apply(List<ProvinceBean> list) throws Exception
                    {
                        for (ProvinceBean data : list)
                        {
                            List<String> cities = new ArrayList<>();
                            for (ProvinceBean.CityBean city : data.getCity())
                            {
                                cities.add(city.getName());
                            }
                            options2Items.add(cities);
                        }
                        return options2Items;
                    }
                })
                .compose(this.<List<List<String>>>bindUntilEvent(ActivityEvent.DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<List<String>>>()
                {
                    @Override
                    public void accept(List<List<String>> lists) throws Exception
                    {
                        mLocationPickView = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener()
                        {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v)
                            {
                                StringBuilder builder = new StringBuilder();
                                builder.append(options1Items.get(options1).getPickerViewText())
                                        .append(" ")
                                        .append(options2Items.get(options1).get(options2));
                                LogUtils.e(builder.toString());
                                mUser.setLocation(builder.toString());
                                modifyUserData();
                            }
                        }).setSubCalSize(20)
                                .setCancelText(getString(R.string.tv_cancel))
                                .setSubmitText(getString(R.string.tv_submit))
                                .setContentTextSize(20).build();
                        mLocationPickView.setPicker(options1Items, options2Items);
                    }
                });
    }


    /*设置性别选择器数据*/
    private void setSexPickData()
    {
        Flowable.create(new FlowableOnSubscribe<List<String>>()
        {
            @Override
            public void subscribe(FlowableEmitter<List<String>> e) throws Exception
            {
                String[] array = getResources().getStringArray(R.array.tv_picker_sex);
                e.onNext(Arrays.asList(array));
                e.onComplete();
            }
        }, BackpressureStrategy.BUFFER)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<String>>()
                {
                    @Override
                    public void accept(final List<String> list) throws Exception
                    {
                        mSexPickView = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener()
                        {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v)
                            {
                                String sex = list.get(options1);
                                LogUtils.e(sex);
                                if (!mTvSexText.getText().toString().equals(sex))
                                {
                                    mUser.setGender(sex.equals(getString(R.string.tv_man)));
                                    modifyUserData();
                                }
                            }
                        }).setSubCalSize(18)
                                .setCancelText(getString(R.string.tv_cancel))
                                .setSubmitText(getString(R.string.tv_submit))
                                .setContentTextSize(18)
                                .build();
                        mSexPickView.setPicker(list);
                    }
                });
    }


    @OnClick({R.id.tv_heade, R.id.tv_nick, R.id.tv_descript, R.id.tv_sex, R.id.tv_city})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.tv_heade://修改头像
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .minSelectNum(1)
                        .isZoomAnim(true)
                        .enableCrop(true)
                        .compress(true)
                        .circleDimmedLayer(true)
                        .cropCompressQuality(70)
                        .rotateEnabled(false)
                        .scaleEnabled(true)
                        .synOrAsy(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.tv_nick://修改昵称:
                openActivityForResult(EditorActivity.class, new EditorDataBean(EditorDataBean.MODIFYNICK, mTvNickText.getText().toString()), EditorDataBean.MODIFYNICK);
                break;
            case R.id.tv_descript://修改个人简介
                openActivityForResult(EditorActivity.class, new EditorDataBean(EditorDataBean.MODIFYDESCRIPT, mTvDescriptText.getText().toString()), EditorDataBean.MODIFYDESCRIPT);
                break;
            case R.id.tv_sex://修改性别
                if (mSexPickView != null)
                {
                    mSexPickView.show();
                }
                break;
            case R.id.tv_city://修改所在地
                if (mLocationPickView != null)
                {
                    mLocationPickView.show();
                }
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            switch (requestCode)
            {
                case EditorDataBean.MODIFYNICK://修改昵称:
                    String nick = data.getStringExtra(this.getClass().getSimpleName());
                    if (mUser != null)
                    {
                        mUser.setNickName(nick);
                        modifyUserData();
                    }
                    break;
                case EditorDataBean.MODIFYDESCRIPT://修改个人简介:
                    String descript = data.getStringExtra(this.getClass().getSimpleName());
                    if (mUser != null)
                    {
                        mUser.setDescription(descript);
                        modifyUserData();
                    }
                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                    if (list != null && (!list.isEmpty()))
                    {
                        LocalMedia media = list.get(0);
                        File file = new File(TextUtils.isEmpty(media.getCompressPath()) ?
                                media.getPath() : media.getCompressPath());
                        mPresenter.setAvatar(file);
                    } else
                    {
                        alert(getString(R.string.alert_choose_picture_fail));
                    }
                    break;
                default:
                    break;
            }
        }
    }


    /*修改用户资料*/
    private void modifyUserData()
    {
        mPresenter.modifyUserData(mUser);
    }


    @Override
    public void showData(Object o)
    {
        super.showData(o);

        if (mUser != null)
        {
            UserBean.updateUserInfo();//更新个人中心用户信息
        }

        if (o instanceof UserBean)
        {
            mUser = (UserBean) o;
            //设置头像
            mUtils.setUserImageResource(mUser.getAvatar(), mImgHeade);
            //设置昵称
            mTvNickText.setText(mUser != null ? mUser.getNickName() : "");
            //设置个人简介
            mTvDescriptText.setText(mUser != null ? mUser.getDescription() : "");
            //地址
            mTvCityText.setText(mUser != null ? mUser.getLocation() : "");
            //性别
            mTvSexText.setText(getString(mUser.isGender() ? R.string.tv_man : R.string.tv_woman));
        }

        if (o instanceof String && ((String) o).startsWith("http"))
        {
            mUtils.setUserImageResource((String) o, mImgHeade);
        }
    }
}
